package org.hole.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hole.common.DomUtil;
import org.hole.common.LogUtil;
import org.hole.web.bean.Treasure;
import org.hole.web.contrl.BrowApiImpl;
import org.hole.web.contrl.BrowerApi;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class BrowerApiServlet extends HttpServlet {
	private static Log log = LogFactory.getLog(BrowerApiServlet.class);
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		log.debug("enter" + LogUtil.arg("req, resp", req, resp));

		String method = req.getParameter("method");
		String paramsStr = req.getParameter("params");
		if (null == method || null == paramsStr) {
			throw new ServletException("No method was specified");
		}
		String[] params = paramsStr.split(",");
		BrowerApi api = new BrowApiImpl();
		ServletOutputStream out = null;
		try {
			out = resp.getOutputStream();
			if (method.equals("open")) {
				open(out, api, params);
			}
		} catch (ParserConfigurationException e) {
			throw new ServletException(e);
		} finally {
			if (null != out) {
				out.close();
			}
		}
		log.debug("leave");
	}

	private void open(ServletOutputStream out, BrowerApi api, String[] params)
			throws IOException, ParserConfigurationException {
		log.debug("enter" + LogUtil.arg("out, api, params", out, api, params));
		List<Treasure> tresure = api.open(params.length > 0 ? params[0] : null);
		Document doc = toDocument(tresure);
		DomUtil.write2OutputStreamFormat(doc, out);
		log.debug("leave");
	}

	private Document toDocument(List<Treasure> tresures)
			throws ParserConfigurationException {
		log.debug("enter" + LogUtil.arg("tresures", tresures));
		Document document = DomUtil.newDocument();
		Element rootEle = document.createElement("Treasures");
		document.appendChild(rootEle);
		for (Treasure tresure : tresures) {
			Element tresureEle = DomUtil
					.createChildElement(rootEle, "Treasure");
			Element tresureIdEle = DomUtil.createChildElement(tresureEle, "Id");
			DomUtil.createChildText(tresureIdEle, tresure.getId());

			Element tresureNameEle = DomUtil.createChildElement(tresureEle,
					"Name");
			DomUtil.createChildText(tresureNameEle, tresure.getName());

			Element tresureIsTagEle = DomUtil.createChildElement(tresureEle,
					"IsTag");
			DomUtil.createChildText(tresureIsTagEle, Boolean.toString(tresure
					.isTag()));
		}
		log.debug("leave");
		return document;
	}
}
